package org.university.repository;

import jakarta.persistence.LockModeType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.university.entity.TeachingClass;

import java.util.Optional;

@Repository
public interface TeachingClassRepository extends JpaRepository<TeachingClass, Integer> {
    Page<TeachingClass> findByDeletedFalse(Pageable pageable);

    /**
     * 检查是否有开设了该课程
     * @param courseId
     * @return 开发该课程的教学班数量，0就是没有开设
     */
    @Query("SELECT COUNT(*) FROM TeachingClass " +
            "WHERE courseId = :courseId")
    Integer isOffering(@Param("courseId") String courseId);

    /**
     * 查询还有生余量的课程
     * @param courseId
     * @return
     */
    @Lock(LockModeType.PESSIMISTIC_WRITE)   // 添加悲观锁防止并发问题
    @Query("SELECT tc FROM TeachingClass tc " +
            "WHERE tc.courseId = :courseId " +
            "AND tc.currentStudents < tc.maxStudents " +
            "AND tc.deleted = 0 " +
            "ORDER BY tc.classId LIMIT 1")
    Optional<TeachingClass> findAvailableClass(@Param("courseId") String courseId);
}